package com.uxsino.simo.indicator.retractor;

import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/*
 * example usage is indicator cpu_usage. title has different name in different linux system. possible title names are
 * separate by @@ in col_id
 */
public class CSVListTitleRetractor extends CSVListRetractor {
    private static Logger logger = LoggerFactory.getLogger(CSVListTitleRetractor.class);

    public CSVListTitleRetractor() {
        super();
    }

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
        String buf = getTable((String) obj);
        String[] lines = getLines(buf);
        if (lines.length < 2) {
            return null;
        }
        ArrayList<Map<String, Object>> records = new ArrayList<Map<String, Object>>();

        String titleLine = lines[0];
        Map<String, Integer> titleMap = new HashMap<>();
        String[] titles = splitRow(titleLine);
        for (int i = 0; i < titles.length; i++) {
            titleMap.put(titles[i], i);
        }

        for (int i = 1; i < lines.length; i++) {
            String[] rec = splitRow(lines[i]);
            if (rec == null) {
                continue;
            }
            HashMap<String, Object> fieldValues = new HashMap<>();
            for (ColumnEntry entry : columnEntries) {
                Object value = null;
                String[] idx = entry.index.split("@@");
                boolean found = false;
                for (int j = 0; j < idx.length && !found; j++) {
                    if (titleMap.containsKey(idx[j])) {
                        found = true;
                        int index = titleMap.get(idx[j]);
                        if (index >= rec.length) {
                            logger.error("index out of range");
                        } else if (!StringUtils.isEmpty(rec[index])) {
                            value = entry.retractor.retract(entity, ctxt, qt, rec[index]);
                            fieldValues.put(entry.field.getName(), value);
                        }
                    }
                }
                if (!found) {
                    logger.error("title line does not contains col_id {}", entry.index);
                }
            }
            records.add(fieldValues);
        }
        return records;
    }

}